<?php
require('../includes/init.php');

//$act = (isset($_POST['act']) && $_POST['act'] <> '') ? $_POST['act'] : '';
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['act'] == 'post')
{
	//header('Content-type:application/json');
	$email = trim($_POST['email']);
	$username = trim($_POST['username']);
	$mobile = trim($_POST['mobile']);
	$referrer = trim($_POST['referrer']);
	$password = $_POST['password'];
	$reg_type = $_POST['reg_type'];
	$captcha  = $_POST['imgcode'];
	$name = trim($_POST['name']);
	$position = trim($_POST['position']);
	$company = trim($_POST['company']);
	
	$res_arr = array(
		'msg' => '',
		'err_id' => '',
		'url' => ''
	);
	
	//err_rstpassword,err_ulike，err_password,err_email
	if(!is_email($email))
	{
		$res_arr = array(
			'msg' => '请输入正确的Email地址',
			'err_id' => 'err_email'
		);
		die(json_encode($res_arr));
	}
	//中文算2个字符
	$temp_len = (strlen ( $username ) + mb_strlen ( $username, 'utf-8' )) / 2;
	//preg_match("/^\D[\x{4e00}-\x{9fa5}a-zA-Z0-9_]+$/u
	if($username=='' || $temp_len<6 || $temp_len>20 || !preg_match("/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_]+$/u", $username))
	{
		$res_arr = array(
			'msg' => '6-20个字符，中文算2个字符;可以用手机号码',
			'err_id' => 'err_ulike'
		);
		die(json_encode($res_arr));
	}
	if($password=='' || strlen($password)<6 || strlen($password)>20)
	{
		$res_arr = array(
			'msg' => '6-20个字符，中文算2个字符',
			'err_id' => 'err_password'
		);
		die(json_encode($res_arr));
	}

	require_once(TMP_PATH . '/config/cfg_username.php');
	$badname_arr = explode(',', $cfg_badname);
	if(in_array($username, $badname_arr))
	{
		$res_arr = array(
			'msg' => '用户名含有非法词，请修改',
			'err_id' => 'err_ulike'
		);
		die(json_encode($res_arr));
	}
	$goodname_arr = explode(',', $cfg_goodname);
	if(in_array($username, $goodname_arr))
	{
		$res_arr = array(
			'msg' => '该用户为系统保留词汇，请修改',
			'err_id' => 'err_ulike'
		);
		die(json_encode($res_arr));
	}
	
	//验证码
	require(ROOT_PATH . '/includes/securimage/securimage.php');
    $securimage = new Securimage();
    if ($securimage->check($captcha) == false) {
    	$res_arr = array(
			'msg' => '验证码错误',
			'err_id' => 'err_imgcode'
		);
		die(json_encode($res_arr));
    }
	
	$sql = "SELECT count(*) FROM `user` WHERE `email`='".$email."';";
	$row = $db->getOne($sql);
	if($row>0)
	{
		$res_arr = array(
			'msg' => '该Email地址已经存在',
			'err_id' => 'err_email'
		);
		die(json_encode($res_arr));
	}
	//用户名
	$sql = "SELECT count(*) FROM `user` WHERE `username`='".$username."';";
	$row = $db->getOne($sql);
	if($row>0)
	{
		$res_arr = array(
			'msg' => '该用户名已经存在',
			'err_id' => 'err_email'
		);
		die(json_encode($res_arr));
	}
	
	$sql = "INSERT INTO `user` SET `username`='".$username."',`email`='".$email."',`mobile`='".$mobile."',`referrer`='".$referrer."',`name`='".$name."',`position`='".$position."',`company`='".$company."',`password`='".md5($password)."',`pwd`='".encrypt($password)."',`reg_type`='".$reg_type."',`created`=NOW();";
	if($db->query($sql))
	{
		$user_id = $db->insert_id();
		//新注册session赋值
		$_SESSION[SESSION_PREFIX]['user_id'] 	= $user_id;
		$_SESSION[SESSION_PREFIX]['username'] 	= $username;
		$_SESSION[SESSION_PREFIX]['user_group'] = '-1';
		$_SESSION[SESSION_PREFIX]['username']   = $username;
		//$_SESSION[SESSION_PREFIX]['email']      = $email;
		$_SESSION[SESSION_PREFIX]['user_rank']  = 0;
		$_SESSION[SESSION_PREFIX]['discount']   = 1.00;
		
		//发送验证邮件
		$uid = $user_id;
		$verify_code = md5($uid.time());
		//更新到数据库
		$sql = "UPDATE `user` SET `email_verify_code`='".$verify_code."' WHERE `user_id`='".$uid."';";
		$db->query($sql);
	
		//邮件里的验证标记
		$ticket = encrypt($uid.'#'.$verify_code);
			
		//邮件标题
		$subject = '邮箱验证邮件';
		$to = $email;
	
		//邮件正文
		$message = '尊敬的 <b>'.$_SESSION[SESSION_PREFIX]['username'].'</b> 您好！<br />
			您于 '.date("Y").'年'.date("m").'月'.date("d").'日 '.date("H").'时'.date("i").'分'.date("s").'秒 申请验证邮箱，点击以下连接，即可完成验证：<br />
			<a href="'.WWW_DOMAIN.'/member/safe/verify_mail_ok.php?v='.$ticket.'">点击这里</a>，立即验证此邮箱。<br />
			如果您点击上述链接无效，请将下面的链接复制到浏览器地址栏中访问：<br />
			http://'.WWW_DOMAIN.'/member/safe/verify_mail_ok.php?v='.$ticket.'<br />
			…………………………<br />
			这是一封系统邮件，请不要回复。<br/>
			';
			
		//@mail($to, $subject, $message, $headers);
		send_mail($_SESSION[SESSION_PREFIX]['username'], $to, $subject, $message, 1);
		//验证邮件
		
		
		//更新购物车里的user_id，永久保存购物车数据
		$sql = "UPDATE `cart` SET `user_id`='".$user_id."' WHERE `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
		$db->query($sql);
		
		//成功
		$return_url = isset($_POST['return_url'])?$_POST['return_url']:'/member/';
		$res_arr = array(
			'msg' => 'success',
			'url' => $return_url
		);
		die(json_encode($res_arr));
	}
	else
	{
		$res_arr = array(
			'msg' => '数据库异常错误',
			'err_id' => 'err_mail'
		);
		die(json_encode($res_arr));
	}
	
}
?>

<?php include('../new/header.php');?>

<link href="/css/v1/register.css?v=2.01" rel="stylesheet" type="text/css" />
<script src="/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/js/artDialog4.1.7/artDialog.js?skin=blue"></script>
<style>
    .wj_sitenav{
        background: white!important;
        z-index: 8888!important;
    }
</style>
<div>
  <div class="fm960">
    <div class="content">
      <div id="register_box">
        <div id="register_left" style="height: 700px;">
          <h1>新用户注册</h1>
          <div id="register_center">
            <div id="register_form">
              <form action="" method="post" id="registFormId">
                <div class="ipt_mail"> <span><span style="color: red;">*</span>电子邮箱：</span>
                  <input id="register_mail" type="text" maxlength="36" name="register_mail" class="text r3" value="" style="border-color: rgb(207, 207, 207);" autocomplete="off">
                  <input type="hidden" id="reg_valid" value="521bfa79397c3" name="reg_valid">
                </div>               
                <div class="ipt_ulike"> <span><span style="color: red;">*</span>用户名：</span>
                  <input id="register_username" style="border-color: rgb(207, 207, 207);" maxlength="36" type="text" name="register_username" class="text r3" value="" autocomplete="off">
                </div>
                <div class="ipt_password"> <span><span style="color: red;">*</span>密码：</span>
                  <input id="register_password" style="border-color: rgb(207, 207, 207);" maxlength="36" type="password" name="register_password" class="text r3">
                </div>
                <div class="ipt_respassword"> <span><span style="color: red;">*</span>确认密码：</span>
                  <input id="register_password2" type="password" maxlength="36" name="register_password2" class="text r3" autocomplete="off" style="border-color: rgb(207, 207, 207);">
                </div>
                <div class="ipt_caigou"> <span>采购类型：</span>
                  <div class="rdo">
                    <input type="radio" name="reg_type" value="企业" checked="checked" class="ck">
                    企业采购
                    <input style="margin-left:10px" type="radio" name="reg_type" value="个人" class="ck">
                    个人采购 </div>
                </div>
                
                 <div class="ipt_company"> <span>真实姓名：</span>
                  <input id="register_name" type="text" maxlength="36" name="register_name" class="text r3" value="" style="border-color: rgb(207, 207, 207);" autocomplete="off">
                </div>
                 <div class="ipt_company"> <span>职务/职位：</span>
                  <input id="register_position" type="text" maxlength="36" name="register_position" class="text r3" value="" style="border-color: rgb(207, 207, 207);" autocomplete="off">
                </div>
                
                 <div class="ipt_mobile"> <span>手机：</span>
                  <input id="register_mobile" type="text" maxlength="36" name="register_mobile" class="text r3" value="" style="border-color: rgb(207, 207, 207);" autocomplete="off">
                </div>
                 <div class="ipt_company"> <span>公司名称：</span>
                  <input id="register_company" type="text" maxlength="36" name="register_company" class="text r3" value="" style="border-color: rgb(207, 207, 207);" autocomplete="off">
                </div>
                
                <div class="ipt_check"> <span style="color: red;">*</span><span>验证码：</span>
                  <input id="imgcode" type="text" maxlength="4" name="imgcode" class="imgtext r3" style="border-color: rgb(207, 207, 207);" onkeyup="this.value = this.value.toUpperCase();">
                <img id="siimage" style="border: 1px solid #000; margin-right: 15px; margin-left:4px; cursor:pointer;" src="../includes/securimage/securimage_show.php?sid=<?php echo md5(uniqid()) ?>" onclick="this.src='../includes/securimage/securimage_show.php?sid='+Math.random()" alt="看不清？换一个" title="看不清？换一个" height="30" align="left" />
             <?php /*?>
             <div style="float:left; width:32px; height:32px; cursor:pointer;">
             <object type="application/x-shockwave-flash" data="../includes/securimage/securimage_play.swf?bgcol=#ffffff&amp;icon_file=../includes/securimage/images/audio_icon.png&amp;audio_file=../includes/securimage/securimage_play.php" height="32" width="32">
            <param name="movie" value="../includes/securimage/securimage_play.swf?bgcol=#ffffff&amp;icon_file=../includes/securimage/images/audio_icon.png&amp;audio_file=../includes/securimage/securimage_play.php" />
            </object>
            </div>
			<?php */?>
            <a tabindex="-1" style="border-style: none;" href="#" title="看不清？换一个" onclick="document.getElementById('siimage').src = '../includes/securimage/securimage_show.php?sid=' + Math.random(); this.blur(); return false"><img src="../includes/securimage/images/refresh.png" alt="Reload Image" height="32" width="32" onclick="this.blur()" align="bottom" border="0" /></a>
                </div>
                  <div class="ipt_referrer"> <span>注册推荐人：</span>
                  <input id="register_referrer" style="border-color: rgb(207, 207, 207);" maxlength="40" type="text" name="register_referrer" class="text r3" value="" autocomplete="off">
                </div>
                <div class="ipt_box">
                  <input class="box fl" id="register_agreement" name="register_agreement" type="checkbox" checked="checked">
                  <span class="fl" style="margin-top:4px;">我已看过并同意《<a href="/help/17.html" target="_blank">本站网络服务使用协议</a>》</span> </div>
                <div class="ipt_sub">
                  <input type="submit" class="sub" value=" ">
                </div>
                <input type="hidden" id="return_url" value="<?php echo $_SERVER['HTTP_REFERER'];?>">
                <input type="hidden" id="act" name="act" value="post">
              </form>
            </div>
            <div id="register_error">
              <div class="err_email"> 请填写您的邮箱地址。如：abc@example.com </div>
              <div class="err_ulike"> 6-20个字符，中文算两个字符。 </div>
              <div class="err_password"> 6-20个字母、数字或者符号 </div>
              <div class="err_rstpassword"> 这里要重复输入一下你的密码 </div>
              <div class="err_mobile">  </div>
              <div class="err_imgcode" style="margin-top:110px;"> 请输入图片中的字符，不区分大小写 </div>
              <div class="err_agree"> <img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">请阅读并同意本站使用协议</span> </div>
              <div class="err_check ipt_check" style="visibility: visible; height: 30px; _margin-top: 60px; margin-top: 60px; margin-left: 50px;width: 250px;"> </div>
            </div>
          </div>
        </div>
        <div id="register_right">
          <div class="rst_login"> <span>已经有帐号？请直接登录</span> <a style="cursor: pointer;" onclick="showLoginDialog()"></a> </div>
          <?php if(0){?>
          <div class="other_login"> <span>您也可以用以下方式登录：</span>
          <a class="o_icon" href="/api/oauth.php?act=login&t=qq" style="background:url(/images/mo/icon_qq_qq.png) no-repeat left center;">QQ 帐号</a>
          <a class="o_icon" href="/api/oauth.php?act=login&t=sina">新浪微博</a>
          <!--
          <a class="o_icon" href="oauth.php?act=login&type=qq" style="background:url(/images/mo/tao.png) no-repeat left center;">淘宝帐号</a>
          <a class="o_icon" href="oauth.php?act=login&type=tencent" style="background:url(/images/mo/icon_qq.png) no-repeat left center;">腾讯微博</a>
          <a class="o_icon" href="oauth.php?act=login&type=renren" style="background:url(/images/mo/icon_ren.png) no-repeat left center;">人人网</a>
          -->
          </div>
          <?php }?>
        </div>
      </div>
      <div class="clear"></div>
    </div>
  <!--  <p class="copyright" title="<?php echo $cfg_site['web_title'];?>">©Copyright 2005-<?php echo date('Y');?> <?php echo $cfg_site['web_title'];?></p>-->
  </div>
  <script type="text/javascript">
	$(function() {
		$("#register_mail").blur(function(){
			var mail = jQuery.trim($('#register_mail').val());
			if(checkEmail(mail))
			{
				$.get('/ajax/user.php',{act:'check', t: 'email', val: mail}, function(data){
					var data = eval("(" + data + ")");
					if(data.msg === 'success')
					{
						$(".err_email").html('<img src="/images/mo/ok_01.png" />');
						return true;
					} else {
						$(".err_email").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">'+data.msg+'</span>')
						return false;
					}
			   });
			}
			else
			{
				return false;
			}
		}).focus(function(){
			$(".err_email").css("visibility", "visible").css("padding-top", "10px").css("height", "26px");
			return false;
		});
		
		//用户名
		$("#register_username").blur(function(){
			var username = jQuery.trim($("#register_username").val());
			if(checkUsername(username))
			{
				$.get('/ajax/user.php',{act:'check', t: 'username', val: username},function(data){
					var data = eval("(" + data + ")");
					if(data.msg === 'success')
					{
						$(".err_ulike").html('<img src="/images/mo/ok_01.png" />');
						return true;
					} else {
						
						$(".err_ulike").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">'+data.msg+'</span>');
						return false;
					}
				});
			}
			else
			{
				return false;
			}
		}).focus(function(){
			$(".err_ulike").css("visibility", "visible").css("padding-top", "10px").css("height", "26px");
			return false;
		});

		// 首次blur验证
		$('#register_password').blur(function() {
			checkPassword();
		}).focus(function(){
			$(".err_password").css("visibility", "visible").css("padding-top", "10px").css("height", "26px");
			return false;
		});
		//验证再次输入的密码
		$('#register_password2').blur(function() {
			checkPassword2();
		}).focus(function(){
			$(".err_rstpassword").css("visibility", "visible").css("padding-top", "10px").css("height", "26px");
		});
		
		$("#imgcode").focus(function(){
			//alert('aaaaa');
			$(".err_imgcode").show();
		});
		

		//发布信息协议
		$('#register_agreement').click(function(){
			$('.err_agree').toggle();
		})
		
		//提交
		$("#registFormId").submit(function(){

			var email = jQuery.trim($('#register_mail').val());
			var mobile = jQuery.trim($('#register_mobile').val());
			var username = jQuery.trim($("#register_username").val());
			var referrer = jQuery.trim($('#register_referrer').val());
			var name = jQuery.trim($('#register_name').val());
			var position = jQuery.trim($('#register_position').val());
			var company = jQuery.trim($('#register_company').val());
			var password = $("#register_password").val();
			var reg_type = $('input[@name=reg_type][checked]').val();
			var imgcode = $("#imgcode").val();
			var return_url = $('#return_url').val();
			//var t = 0;
			if(checkEmail(email))
			{
				$.get('/ajax/user.php',{act:'check', t: 'email', val: email},function(data){
					var data = eval("(" + data + ")");
					if(data.msg === 'success')
					{
						$(".err_email").html('<img src="/images/mo/ok_01.png" />');
						return true;
					} else {
						$(".err_email").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">'+data.msg+'</span>')
						return false;
					}
			   });
			}
			else
			{
				return false;
			}
			if(checkUsername(username))
			{
				$.get('/ajax/user.php?act=check',{act:'check', t: 'username', val: username},function(data){
					var data = eval("(" + data + ")");
					if(data.msg === 'success')
					{
						$(".err_ulike").html('<img src="/images/mo/ok_01.png" />');
						return true;
					} else {
						
						$(".err_ulike").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">'+data.msg+'</span>');
						return false;
					}
				});
			}
			else
			{
				return false;
			}
			if(!checkPassword())
			{
				return false;
			}
			if(!checkPassword2())
			{
				return false;
			}
			//is_submit = true;
			
			$.post("register.php", {'act': 'post', 'email': email,'mobile': mobile,'referrer': referrer,'name': name,'position': position,'company': company, 'imgcode': imgcode, 'password': password, 'reg_type': reg_type, 'username': username,'url':return_url}, function(rs){
				var rs = eval("(" + rs + ")");
				if(rs.msg == "success") {
					//window.location.href = rs.url;
					art.dialog({
						content: '注册成功，3秒后自动跳转',
						time: 3,
						lock: true,
						close: function(){
							window.location.href = "../new/index.php";
						}
					});
					return;
				}
				else
				{
					$("."+rs.err_id).html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">'+rs.msg+'</span>').show();
					return false;
				}
			});
			return false;
			
		});
	});//$结束
	
	//判断用户名是否合法
	function checkEmail(mail)
	{
		if(mail.length != 0) {
			if(!isMail(mail)) {
				$(".err_email").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">请输入正确的Email地址</span>');
				return false;
			}
			else { //判断邮箱是否已存在
				return true;
			}
		}
		else{
			$(".err_email").css("visibility", "visible").css("padding-top", "10px").css("height", "26px");
			return false;
		}
	}
	
	function checkUsername(username)
	{
		if(username == ''){
			$(".err_ulike").css("visibility", "visible").css("padding-top", "10px").css("height", "26px");
			return false;
		}
		if(isSpecialCh(username)) {
			$(".err_ulike").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">不能含有特殊字符</span>');
			return false;
		}
		if(strlen(username) < 6 || strlen(username) > 20) {
			$(".err_ulike").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">不能数字开头，6-20个字符，中文算2个字符</span>');
			return false;
		}
		//过滤含有特定词的昵称
		if (username.indexOf("五联") >= 0 || username.indexOf("pentalink") >= 0) {
			$(".err_ulike").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">不能含“五联”、“pentalink”等专用词</span>');
			return false;
		}
		else
		{
			return true;
		}	
	}
	
	function checkPassword()
	{
		var pwd = $('#register_password').val();
		if(pwd.length == 0) {
			$(".err_password").css("visibility", "visible").css("padding-top", "10px").css("height", "26px");
			return false;
		}
		else {
			if(pwd.length < 6 || pwd.length > 20) {
				$(".err_password").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">6-20个字母、数字或者符号</span>');
				return false;
			}
			else {
				$(".err_password").html('<img src="/images/mo/ok_01.png" />');
				return true;
			}
		}
	}
	
	function checkPassword2()
	{
		var pwd = $('#register_password').val();
		var pwd2 = $('#register_password2').val();
		if(pwd2.length == 0) {
			$(".err_rstpassword").css("visibility", "visible").css("padding-top", "10px").css("height", "26px");
			return false;
		}
		else {
			if(pwd != pwd2) {
				$(".err_rstpassword").html('<img src="/images/mo/error1.png" /><span style="color:#c91623; margin-left:8px; margin-top:0;">6-20个字母、数字或者符号</span>');
				return false;
			}
			else {
				$(".err_rstpassword").html('<img src="/images/mo/ok_01.png" />');
				return true;
			}
		}
	}

	function isMail(mail) {
		return /^[0-9a-z_][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}\.){1,4}[a-z]{2,4}$/i.test(mail);
	}

	function strlen(str){
	    var len = 0;
	    for (var i=0; i<str.length; i++) {
	     var c = str.charCodeAt(i);
	    //单字节加1
	     if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
	       len++;
	     }
	     else {
	      len+=2;
	     }
	    }
	    return len;
	}

	function isSpecialCh(str)
	{
		var tt = str.replace(/[a-zA-Z\d_]/g, "");
		tt = tt.replace(/[\u4e00-\u9fa5]/g, "");

		if(tt.length > 0) {
			return true;
		}
		else {
			return false;
		}
	}
</script> 
</div>

<?php include('../new/footer.php');?>